import path from 'path'
import moment from 'moment'
import readline from 'readline'
import fse from 'fs-extra'
const LOGS_FOLDER = path.resolve('logs');
const getHourlyStats = async () => {
    const hourlyData = Array(24).fill().map(() => ({
        count: 0,
        totalDuration: 0,
        errorCount: 0
    }));

    const date = moment().format('YYYY-MM-DD') + '.log'
    const logPath = path.join(LOGS_FOLDER, date);

    const fileStream = fse.createReadStream(logPath);
    const rl = readline.createInterface({
        input: fileStream,
        crlfDelay: Infinity
    });

    for await (const line of rl) {
        try {
            const logEntry = JSON.parse(line);
            if (logEntry.message !== 'HTTP') {
                continue;
            }
            const hour = moment(logEntry.timestamp).hour();
            hourlyData[hour].count++;
            hourlyData[hour].totalDuration += logEntry.duration || 0;
            if (logEntry.status >= 400) {
                hourlyData[hour].errorCount++;
            }
        } catch (err) {
            console.log('读取一行日志失败：', line)
            console.error('Error parsing log line:', err);
        }
    }

    return hourlyData.map((data, hour) => ({
        hour,
        count: data.count,
        avgDuration: data.count > 0 ? Math.round(data.totalDuration / data.count) : 0,
        errorRate: data.count > 0 ? parseFloat(((data.errorCount / data.count) * 100).toFixed(2)) : 0
    }));
}

export default getHourlyStats